<template>
  <div>
    <el-button type="primary" class="mb-4" @click="addLanguage">新增</el-button>
    <el-table :data="tableData" height="85vh" ref="dragCurrency">
      <el-table-column width="30" align="center">
        <template #default="scope">
          <i class="icon-handle">
            <el-icon>
              <DCaret />
            </el-icon>
          </i>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID"  width="150"/>
      <el-table-column prop="name" label="货币名" />
      <el-table-column prop="description" label="中文名" />
      <el-table-column prop="code" label="货币代码" />
      <el-table-column prop="symbol" label="货币符号"  />

      <el-table-column prop="payTime" label="符号靠左" align="center">
        <template #default="scope">
          <el-switch :width="58" v-model="scope.row.isLeftSymbol" :active-value="true" :inactive-value="false"
            active-text="是" inactive-text="否" disabled inline-prompt />
        </template>
      </el-table-column>

      <el-table-column prop="payTime" label="状态" align="center">
        <template #default="scope">
          <el-switch :width="58" v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
            inactive-text="关闭" inline-prompt :disabled="scope.row.disabled" :loading="switchStatus"
            @change="switchProcess(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column prop="newTime" label="修改时间" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" v-if="!scope.row.disabled">
            编辑
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="title" :before-close="handleClose" width="500px">
      <el-form :model="languageParams" ref="currencyForm" label-position="left" :rules="languageRules">
        <el-form-item label="货币英文" prop="name" required>
          <el-input v-model.trim="languageParams.name" placeholder="请输入（英文）" />
        </el-form-item>
        <el-form-item label="货币中文" prop="description" required>
          <el-input v-model.trim="languageParams.description" placeholder="请输入（中文）" />
        </el-form-item>
        <el-form-item label="货币代码" prop="code" required>
          <el-input v-model.trim="languageParams.code" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="货币符号" prop="symbol" required>
          <el-input v-model.trim="languageParams.symbol" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="开启状态" prop="status" required>
          <el-switch :width="58" v-model="languageParams.status" :active-value="1" :inactive-value="0" inline-prompt
            active-text="开启" inactive-text="关闭" />
        </el-form-item>
        <el-form-item label="符号靠左" prop="isLeftSymbol" required>
          <el-switch :width="58" v-model="languageParams.isLeftSymbol" :active-value="true" :inactive-value="false"
            inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSure(currencyForm)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { status } from "nprogress";
import { ref, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const publicItem = ref({});
const dialogVisible = ref(false); //默认不显示弹出框
const tableData = ref([]);
const title = ref("新增");
const isAdd = ref(true); //默认是新增
const switchStatus = ref(false);

const currencyForm = ref();
const languageParams = ref({
  name: "", //货币名
  description: "", //中文
  code: "", //货币代码
  symbol: "", //货币符号
  status: 1, //开启状态
  isLeftSymbol: true, //符号靠左状态
});
const languageRules = reactive({
  name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
    {
      pattern: /^[A-Za-z\s]*$/,
      message: "只能输入英文",
      trigger: "blur",
    },
  ],
  description: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
    {
      pattern: /^[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]+$/,
      message: "只能输入中文",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
    {
      pattern: /^[A-Z]+$/,
      message: "只能输入大写的英文",
      trigger: "blur",
    },
  ],
  symbol: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  leftSymbol: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  getList();
  handleDrag()
});
// 获取列表
const getList = () => {
  product.currency
    .currencyList({
      params: {
        status: 1,
      },
    })
    .then((res) => {
      res.data = res.data.map((code) => {
        return {
          ...code,
          disabled: code.id === 7 || code.id === 2 ? true : false,
          newTime:  proxy.DateTime(code.lastModified),
        };
      });
      tableData.value = res.data;
    });
};
// 编辑
const handleEdit = (rowItem) => {
  publicItem.value = rowItem;
  dialogVisible.value = true;
  isAdd.value = false;
  title.value = "编辑";

  languageParams.value.name = rowItem.name;
  languageParams.value.description = rowItem.description;
  languageParams.value.code = rowItem.code;
  languageParams.value.symbol = rowItem.symbol;
  languageParams.value.status = rowItem.status;
  languageParams.value.isLeftSymbol = rowItem.isLeftSymbol;
};
const addLanguage = () => {
  dialogVisible.value = true;
  title.value = "新增";
  isAdd.value = true;
};
// 取消
const handleClose = () => {
  proxy.resetForm("currencyForm");
  isAdd.value = false;
  dialogVisible.value = false;
  languageParams.value.name = ''
  languageParams.value.description = ''
  languageParams.value.code = ''
  languageParams.value.symbol = ''
  languageParams.value.status = 1
  languageParams.value.isLeftSymbol = true

};
// 确定
const handleSure = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        product.currency.currencyAdd({
          data: languageParams.value,
        })
          .then((res) => {
            if (res.code === 200) {
              handleClose();
              getList();
              proxy.$modal.msgSuccess("新增成功");
            }
          });
      } else {
        product.currency.currencyUpdate({
          pathParams: {
            id: publicItem.value.id,
          },
          data: languageParams.value,
        })
          .then((res) => {
            if (res.code === 200) {
              handleClose();
              getList();
              proxy.$modal.msgSuccess("修改成功");
            }
          });
      }
    }
  });
};
// 删除
const handleDelete = (rowItem) => {
  var newArray = [];
  newArray.push(rowItem.id);
  proxy.$modal.confirm("是否确认删除此数据类型？").then(() => {
    product.currency.currencyDeletebatch({
      data: {
        ids: newArray,
      },
    })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        }
      });
  });
};
const switchProcess = (rowItem) => {
  console.log(rowItem);
  switchStatus.value = true;



  proxy.$modal
    .confirm("是否确认修改此数据类型？")
    .then(() => {
      product.currency.currencyUpdatestatus({
        pathParams: {
          id: rowItem.id,
        },
        params: {
          status: rowItem.status,
        },
      })
        .then((res) => {
          if (res.code === 200) {
            switchStatus.value = false;
            getList();
            proxy.$modal.msgSuccess(res.message);
          }
        });
    })
    .catch((err) => {
      switchStatus.value = false;
      if (rowItem.status) {
        return (rowItem.status = 0);
      } else {
        return (rowItem.status = 1);
      }
    });
};
const handleDrag = () => {
  const elTableBody = proxy.$refs["dragCurrency"].$el.querySelector(
    ".el-table__body-wrapper tbody"
  );
  proxy.Sortable.create(elTableBody, {
    animation: 150, // 拖拽动画
    handle: ".icon-handle", // 把手选择器
    filter: ".no-drag", // 禁用拖拽的类
    ghostClass: "blue-background-class",
    onEnd: (event) => {
      const { oldIndex, newIndex } = event;
      console.log(oldIndex, newIndex);
      // 调整数据顺序
      const movedItem = tableData.value.splice(oldIndex, 1)[0];
      tableData.value.splice(newIndex, 0, movedItem);
      let ids = tableData.value.map(code => code.id)
      product.currency.currencyUpdatesort({
        data: {
          ids: ids
        }
      }).then(res => {
        if (res.code === 200) {
          tableData.value = []
          getList();
        }
      })
    },
  });
}



</script>